package com.xjnt.base.support.admin.service;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.xjnt.base.support.admin.entity.Account;
import com.xjnt.base.support.admin.entity.Group;
import com.xjnt.frameworks.annotation.Service;
//import com.xjnt.frameworks.core.BaseModel;
import com.xjnt.frameworks.core.BaseService;
import com.xjnt.frameworks.plugin.sql.SqlKit;
import com.xjnt.frameworks.plugin.sql.criterion.Restrictions;
import com.xjnt.frameworks.plugin.sql.criterion.SqlCriteria;

@Service
public class AccountService extends BaseService<Account> {
	
	@Override
	public Account getModel() {
		return Account.me;
	}
	
	public Account findByName(String username){
		SqlCriteria criteria = new SqlCriteria(getModel());
		criteria.add(Restrictions.eq(Account.USERNAME, username));
		return getModel().findFirst(criteria.toSql(), username);
	}
	
	public Account findByEmail(String email){
		SqlCriteria criteria = new SqlCriteria(getModel());
		criteria.add(Restrictions.eq(Account.EMAIL, email));
		return getModel().findFirst(criteria.toSql(), email);
	}
	
	public Account findByMobile(String mobile){
		SqlCriteria criteria = new SqlCriteria(getModel());
		criteria.add(Restrictions.eq(Account.MOBILE, mobile));
		return getModel().findFirst(criteria.toSql(), mobile);
	}
	
	public Account findByUserId(String userId){
		SqlCriteria criteria = new SqlCriteria(getModel());
		criteria.add(Restrictions.eq(Account.FK_USERID, userId));
		return getModel().findFirst(criteria.toSql(), userId);
	}
	
	public void allocGroups(String accountId, List<Group> groups){
		for (Group group : groups) {
			Db.update(SqlKit.findSql("Account.relationGroup"), accountId, group.getStr(Group.PK_ID));
		}
	}
	
	public void removeGroups(String accountId, List<Group> groups){
		for (Group group : groups) {
			Db.update(SqlKit.findSql("Account.removeGroup"), accountId, group.getStr(Group.PK_ID));
		}
	}
}
